while
¶Consider the following task: fill the bottom row of a bit world with green.
while
¶ever_green.py
¶while <condition>:
if the condition was True
run these lines
then check the condition again
Repeating the same lines of code is called a loop.
A loop body contains the instructions we want to run multiple times.
The loop condition determines whether the loop body will be run.
The loop body is indented 4 spaces relative to the while
statement.
Ideally, we would have something that was True
when it was ok for Bit to move and False
when Bit was blocked.
Bit has a method for checking whether the front of Bit is clear (i.e. a move will not go out of bounds).
bit.front_clear()
It returns True
when the space in front of Bit is clear and False
when the space in front is blocked.
go_green.py
¶green_blue.py
¶A condition is something that is either true or false.
We can represent the concept of true or false in python using the values True
and False
.
A thing that is either True
or False
is called a boolean (named after George Boole).
paint_move.py
¶When using while
loops, always consider the boundary conditions.
A boundary condition is the state of your program when a loop starts or finishes.
For example:
while
loop, be clear about the boundary conditions.
Sometimes a Bit world includes black squares. These squares are blocked; Bit cannot move onto them.
Besides front_clear()
, Bit can also check left_clear()
and right_clear()
.
not
¶You can turn a True
to False
and a False
to True
using the not
keyword.
Bit can tell you what color it is sitting on.
bit.is_blue()
bit.is_green()
bit.is_red()
bit.is_empty()
while True
¶What happens when the condition of a while
loop is always True
?
infinite_loop.py
¶Now that you have these colors and tools at your command, let's paint something.
fix_tree.py
¶Bit has a nice tree in his yard, but it is missing its trunk!
Help Bit fix the tree by adding the trunk.
Get Bit to the red square
Fill in the trunk
Bit gives us move
, paint
, etc.
What new verbs would make this job even easier?
while
not
New Bit methods
bit.front_clear()
bit.left_clear()
bit.right_clear()
bit.is_blue()
bit.is_green()
bit.is_red()
bit.is_empty()